import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:recipe/module/search.dart';

import 'info.dart';
import 'module/api.dart';
import 'module/banner.dart';
import 'module/globalColor.dart';

class HomePage extends StatefulWidget {
  HomePage({Key key}) : super(key: key);
  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  ScrollController _listController = ScrollController();
  String searchTitle = "";
  bool listLoading = false;
  int page = 2;
  List foodList = [];
  List menuList = [];
  List bannerList = [];
  @override
  void initState() {
    EasyLoading.instance.loadingStyle = EasyLoadingStyle.light;
    EasyLoading.instance.maskType = EasyLoadingMaskType.black;
    _listController.addListener(() {
      if (_listController.position.pixels >=
          _listController.position.maxScrollExtent) {
        if (page > 200) {
          EasyLoading.showToast('没有更多了');
          return;
        }
        if (!listLoading) {
          setState(() => {listLoading = true});
          EasyLoading.show(status: '加载中');
          getFoodList(page, 102, 'tag', '').then((res) {
            setState(() {
              foodList.addAll(res['data']);
              listLoading = false;
              EasyLoading.dismiss();
              page++;
            });
          });
        }
      }
    });

    getFoodList(1, 102, 'tag', '').then((res) {
      setState(() {
        foodList = res['data'];
        menuList = res['label'];
        bannerList = [
          res['data'][5],
          res['data'][10],
          res['data'][15],
          res['data'][20]
        ];
        print("asdasd${bannerList}");
        listLoading = false;
      });
    });
    super.initState();
  }

  // 获取实物列表
  getFoodList(int page, int type, String order, String searchFlag) async {
    String url =
        "home_list?page=${page.toString()}&type=${type.toString()}&order=${order}";

    if (searchFlag != "") {
      url = "search?page=${page.toString()}&name=${searchFlag}";
    }

    try {
      var response = await HttpRequest.request(url, method: HttpRequest.GET);
      return response;
    } catch (e) {
      print(e);
    }
  }

  List<Widget> renderFoodList(foodList) {
    List<Widget> list = [
      SizedBox(height: 10),
      Row(
        children: [
          SizedBox(width: 10),
          Padding(
              padding: EdgeInsets.only(top: 20, bottom: 20),
              child: Text(
                "最新发布：",
                maxLines: 5,
                overflow: TextOverflow.ellipsis,
                style: TextStyle(
                  fontSize: 28,
                  fontWeight: FontWeight.w700,
                ),
              ))
        ],
      ),
      SizedBox(height: 10),
    ];
    List.generate(foodList.length, (index) {
      String str = json.encode(foodList[index]);
      final item = json.decode(str);
      list.add(Padding(
        padding: EdgeInsets.only(bottom: 12),
        child: InkWell(
            onTap: () {
              Navigator.push(
                context,
                MaterialPageRoute(
                  builder: (context) => Info(infoId: item['id'].toString()),
                ),
              );
            },
            child: Container(
              decoration: BoxDecoration(
                color: Colors.white,
                boxShadow: [
                  BoxShadow(
                      color: Colors.grey[200],
                      offset: Offset(1.0, 2.0), //阴影xy轴偏移量
                      blurRadius: 1.0, //阴影模糊程度
                      spreadRadius: 1.0 //阴影扩散程度
                      ),
                ],
              ),
              padding: EdgeInsets.only(bottom: 15, left: 8, right: 8),
              width: MediaQuery.of(context).size.width / 2,
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.center,
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Container(
                      height: 200,
                      child: ClipRRect(
                        borderRadius: BorderRadius.all(Radius.circular(5)),
                        child: FadeInImage.assetNetwork(
                          placeholder: 'assets/images/cover.jpg',
                          fadeInDuration: const Duration(milliseconds: 500),
                          image: item['fcover'],
                          fit: BoxFit.cover,
                        ),
                      )),
                  SizedBox(height: 5),
                  Container(
                    padding: EdgeInsets.only(left: 15, right: 15),
                    child: Column(
                      children: [
                        Text(
                          item['title'],
                          maxLines: 1,
                          overflow: TextOverflow.ellipsis,
                          style: TextStyle(
                            color: Colors.black,
                            fontSize: 18,
                            fontWeight: FontWeight.w500,
                          ),
                        ),
                      ],
                    ),
                  )
                ],
              ),
            )),
      ));
    });
    return list;
  }

  @override
  Widget build(BuildContext context) {
    List topDom = [
      Search(
          clickGetFoodList: (page, type, order, searchFlag) => {
                EasyLoading.show(status: '搜索中'),
                getFoodList(page, type, order, searchFlag).then((res) => {
                      EasyLoading.dismiss(),
                      setState(() {
                        foodList = res['data'];
                      })
                    })
              }),
      Container(
        padding: EdgeInsets.only(left: 15, right: 15, top: 15),
        child: new BannerWidget(
          180.0,
          initBanner(bannerList),
          bannerPress: (pos, item) {
            print('第 $item 点击了');
            Navigator.push(
              context,
              MaterialPageRoute(
                builder: (context) =>
                    Info(infoId: bannerList[pos]["id"].toString()),
              ),
            );
          },
        ),
      ),
      SizedBox(height: 10),
    ];

    List emptyData = [];
    if (renderFoodList(foodList).length == 0) {
      emptyData = [
        Container(
            padding: EdgeInsets.only(top: 60),
            child: Center(child: Text("~暂没有数据~")))
      ];
    }

    return menuList.length > 0
        ? Scaffold(
            appBar: AppBar(title: Text("厨神在家")),
            backgroundColor: Colors.white,
            body: Container(
              width: MediaQuery.of(context).size.width,
              padding: EdgeInsets.only(top: 10),
              child: SingleChildScrollView(
                  controller: _listController,
                  child: Wrap(
                    children: [
                      ...topDom,
                      ...renderFoodList(foodList),
                      ...emptyData
                    ],
                  )),
            ))
        : Column(
            crossAxisAlignment: CrossAxisAlignment.center,
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              CircularProgressIndicator(
                  valueColor: new AlwaysStoppedAnimation<Color>(
                      GlobalColor.themeColor)),
              SizedBox(height: 20),
              Text(
                "正在加载",
              )
            ],
          );
  }

  // 初始化 banner 图列表
  List<BannerItem> initBanner(arr) {
    List<BannerItem> bannerList = [];
    List.generate(arr.length, (index) {
      bannerList.add(BannerItem.defaultBannerItem(
          arr[index]["fcover"],
          arr[index]["message"] == ''
              ? "${arr[index]["title"]}"
              : arr[index]["message"]));
    });
    return bannerList;
  }
}
